<template>
  <div>
    <h2>实时数据推送</h2>
    <echart v-if="Flag" :myOption="charLeftBottom" :myStyle="{ width: '100%', height: '300px' }" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue';
// 时间格式化js库
import dayjs from "dayjs";
import echart from '../components/MyEcharts.vue'
// 图表options
import { charLeftBottom } from '../utils/echartsOption.ts';

const Flag = ref<boolean>(false);
// let key = ref(0)
// 获取当前时间
let currentTime = Date.now();
// 设置x轴时间
const data = reactive([
  dayjs(currentTime - 210000).format('HH:mm:ss'),
  dayjs(currentTime - 180000).format('HH:mm:ss'),
  dayjs(currentTime - 150000).format('HH:mm:ss'),
  dayjs(currentTime - 120000).format('HH:mm:ss'),
  dayjs(currentTime - 90000).format('HH:mm:ss'),
  dayjs(currentTime - 60000).format('HH:mm:ss'),
  dayjs(currentTime - 30000).format('HH:mm:ss')
]);
/**
 * 功能方法
 */

// 接收后端实时推送的数据
const getStudentStatsDistriLeftBottom = function () {
  // 创建socket实例
  let ws = new WebSocket("ws://localhost:3002/bigscreen/websockets?id=10086");
  ws.onmessage = function (result) {
    // DOM监听key值的变化,重新加载页面
    // key.value++
    console.log(result, '111111111111')

    Flag.value = false;
    Promise.resolve().then(() => {
      console.log("后端推送数据", JSON.parse(result.data))
      // 后端数据
      let leftBottomData = JSON.parse(result.data)
      // console.log(leftBottomData, '1111111')
      // options数据重新处理
      let SeriesData = []
      for (let i = 0; i < leftBottomData.seriesData.length; i++) {
        let seriesDataItem = {
          name: leftBottomData.legendData[i],
          type: 'line',
          stack: 'Total',
          smooth: true,
          symbol: 'none',
          data: leftBottomData.seriesData[i]
        }
        SeriesData.push(seriesDataItem)
      }
      charLeftBottom.legend.data = leftBottomData.legendData;
      charLeftBottom.xAxis.data = data;
      charLeftBottom.series = SeriesData;
      Flag.value = true
    })
  }
}
function getXaisData() {
  var timer = null;
  timer = setInterval(() => {
    data.shift();
    data.push(dayjs(new Date()).format('HH:mm:ss'));
    console.log(data);
  }, 30000);
  return data;
}
watch(data, () => {
  // 为了重新渲染echarts
  getStudentStatsDistriLeftBottom()
})

onMounted(() => {
  getStudentStatsDistriLeftBottom()
  getXaisData()
})

</script>

<style lang="scss" scoped></style>